package Operate;
import User.User;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Set;



public class Register{
    //检查用户名是否已经被使用
    private static Set<String> registeredUsernames = new HashSet<>();

    public static void register() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入您的用户名:");
        String username = scanner.nextLine();

        boolean usernameExists = checkUsernameExists(username);

        if (usernameExists) {
            System.out.println("用户名已被使用，请重新输入。");
            register();
        } else {
            System.out.println("请输入您的密码:");
            String password = scanner.nextLine();
            User.user(username, password);
        }
    }

    private static boolean checkUsernameExists(String username) {
        if (registeredUsernames.contains(username)) {
            return true;
        }
//检查用户名是否已经使用
        try {
            File file = new File("UserInformation");
            if (file.exists()) {
                Scanner fileScanner = new Scanner(file);
                while (fileScanner.hasNextLine()) {
                    String line = fileScanner.nextLine();
                    String[] parts = line.split(",");
                    String registeredUsername = parts[0].trim();
                    registeredUsernames.add(registeredUsername);
                    if (registeredUsername.equals(username)) {
                        fileScanner.close();
                        return true;
                    }
                }
                fileScanner.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        registeredUsernames.add(username);
        return false;
    }
}

